<template>
  <!-- 会员管理 -->
  <div>
    <div class="toolbar">
      <el-input v-model="memberSearch" placeholder="搜索会员" style="width: 200px;" clearable @input="handleSearch" />
      <el-button type="primary" @click="handleAddMember">添加会员</el-button>
    </div>

    <el-table :data="members" style="width: 100%" border>
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="position" label="职位" width="120" />
      <el-table-column prop="phone" label="联系电话" width="150" />
      <el-table-column prop="address" label="地址" />
      <el-table-column prop="joinDate" label="入会日期" width="120" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="handleViewMember(scope.row)">详情</el-button>
          <el-button size="small" @click="handleEditMember(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDeleteMember(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination v-if="totalMembers > 0" class="pagination" :current-page="currentPage" :page-size="pageSize"
      :total="totalMembers" layout="total, prev, pager, next" @current-change="handlePageChange" />

    <!-- 会员编辑对话框 -->
    <el-dialog v-model="memberDialogVisible" :title="memberForm.id ? '编辑会员' : '添加会员'" width="60%" top="5vh"
      append-to-body>
      <el-form ref="memberFormRef" :model="memberForm" :rules="memberFormRules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="memberForm.id ? 12 : 8">
            <el-form-item label="会员类型">
              <el-select v-model="memberForm.memberType" placeholder="请选择会员类型">
                <el-option label="文史会员" value="A" />
                <el-option label="联盟成员" value="B" />
                <el-option label="联盟企业" value="C" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="memberForm.id ? 12 : 8">
            <el-form-item label="职位">
              <el-select v-model="memberForm.position" placeholder="请选择职位">
                <el-option v-for="item in availablePositions" :key="item.id" :label="item.name" :value="item.name" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="!memberForm.id">
            <el-form-item label="关联会员">
              <el-select v-model="memberForm.userId" placeholder="请选择关联会员">
                <el-option v-for="item in clanMembers" :key="item.id" :label="`${item.nickname} - ${item.username}`" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 基本信息 -->
        <el-divider>基本信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名">
              <el-input v-model="memberForm.name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别">
              <el-select v-model="memberForm.gender" placeholder="请选择性别">
                <el-option label="男" value="男" />
                <el-option label="女" value="女" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生年月">
              <el-date-picker v-model="memberForm.birthDate" type="date" placeholder="选择日期" format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="籍贯">
              <el-input v-model="memberForm.nativePlace" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="民族">
              <el-input v-model="memberForm.ethnicity" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="文化程度">
              <el-select v-model="memberForm.education" placeholder="请选择文化程度">
                <el-option label="小学" value="小学" />
                <el-option label="初中" value="初中" />
                <el-option label="高中" value="高中" />
                <el-option label="专科" value="专科" />
                <el-option label="本科" value="本科" />
                <el-option label="硕士" value="硕士" />
                <el-option label="博士" value="博士" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="政治面貌">
              <el-select v-model="memberForm.politicalStatus" placeholder="请选择政治面貌">
                <el-option label="群众" value="群众" />
                <el-option label="共青团员" value="共青团员" />
                <el-option label="中共党员" value="中共党员" />
                <el-option label="民主党派" value="民主党派" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="专长">
              <el-input v-model="memberForm.specialty" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 联系方式 -->
        <el-divider>联系方式</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="memberForm.phone" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电子邮箱" prop="email">
              <el-input v-model="memberForm.email" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证号码" prop="idCard">
              <el-input v-model="memberForm.idCard" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="通讯地址">
              <el-input v-model="memberForm.address" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 企业信息（仅B类和C类显示） -->
        <template v-if="memberForm.memberType === 'B' || memberForm.memberType === 'C'">
          <el-divider>企业信息</el-divider>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="企业名称">
                <el-input v-model="memberForm.companyName" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="企业职务">
                <el-input v-model="memberForm.companyPosition" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="注册资金">
                <el-input-number v-model="memberForm.registeredCapital" :min="0" :step="100" />
                <span class="form-tip">万元</span>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="企业地址">
                <el-input v-model="memberForm.companyAddress" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="经营范围">
                <el-input type="textarea" v-model="memberForm.businessScope" :rows="3" />
              </el-form-item>
            </el-col>
          </el-row>
        </template>

        <!-- 其他信息 -->
        <el-divider>其他信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入会日期">
              <el-date-picker v-model="memberForm.joinDate" type="date" placeholder="选择日期" format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="家族关系">
              <el-input v-model="memberForm.familyRelation" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input type="textarea" v-model="memberForm.remarks" :rows="3" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 照片上传 -->
        <el-divider>个人照片</el-divider>
        <el-form-item>
          <el-upload class="avatar-uploader" action="/api/upload" :show-file-list="false"
            :on-success="handlePhotoSuccess" :before-upload="beforePhotoUpload">
            <img v-if="memberForm.photoUrl" :src="memberForm.photoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="memberDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveMember">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 会员详情对话框 -->
    <el-dialog v-model="memberDetailVisible" title="会员详情" width="60%" top="5vh" append-to-body>
      <el-descriptions v-if="currentMember" :column="2" border>
        <el-descriptions-item label="姓名">{{ currentMember.name }}</el-descriptions-item>
        <el-descriptions-item label="职位">{{ currentMember.position }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{ currentMember.gender }}</el-descriptions-item>
        <el-descriptions-item label="出生年月">{{ currentMember.birthDate }}</el-descriptions-item>
        <el-descriptions-item label="籍贯">{{ currentMember.nativePlace }}</el-descriptions-item>
        <el-descriptions-item label="民族">{{ currentMember.ethnicity }}</el-descriptions-item>
        <el-descriptions-item label="文化程度">{{ currentMember.education }}</el-descriptions-item>
        <el-descriptions-item label="政治面貌">{{ currentMember.politicalStatus }}</el-descriptions-item>
        <el-descriptions-item label="专长">{{ currentMember.specialty }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ currentMember.phone }}</el-descriptions-item>
        <el-descriptions-item label="身份证号码">{{ currentMember.idCard }}</el-descriptions-item>
        <el-descriptions-item label="通讯地址">{{ currentMember.address }}</el-descriptions-item>
        <el-descriptions-item label="入会日期">{{ currentMember.joinDate }}</el-descriptions-item>
        <el-descriptions-item label="会员类型">
          {{ {
            'A': '文史会员',
            'B': '联盟成员',
            'C': '联盟企业'
          }[currentMember.memberType] || '普通会员' }}
        </el-descriptions-item>
        <el-descriptions-item label="电子邮箱">{{ currentMember.email }}</el-descriptions-item>
        <el-descriptions-item label="家族关系">{{ currentMember.familyRelation }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ currentMember.remarks }}</el-descriptions-item>
      </el-descriptions>
      <div class="image-preview" v-if="currentMember && currentMember.photoUrl">
        <div class="preview-item">
          <h4>个人照片</h4>
          <el-image :src="currentMember.photoUrl" :preview-src-list="[currentMember.photoUrl]" fit="cover"
            style="width: 100px; height: 100px" />
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="memberDetailVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleEditMember(currentMember)">编辑</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import ClanMemberAPI from "@/api/clanMember/clanMember"

const props = defineProps({
  templeId: {
    type: [String, Number],
    required: true
  },
  positions: {
    type: Array,
    default: () => []
  },
  clanMembers: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:members'])

// 会员管理
const members = ref([])
const memberSearch = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalMembers = ref(0)
const memberDialogVisible = ref(false)
const memberDetailVisible = ref(false)
const currentMember = ref(null)

const memberForm = ref({
  id: null,
  name: '',
  gender: '',
  birthDate: '',
  nativePlace: '',
  ethnicity: '',
  education: '',
  politicalStatus: '',
  specialty: '',
  phone: '',
  idCard: '',
  address: '',
  position: '',
  joinDate: '',
  memberType: 'A',
  // B类和C类特有字段
  companyName: '',
  companyPosition: '',
  registeredCapital: '',
  companyAddress: '',
  businessScope: '',
  // 其他字段
  email: '',
  familyRelation: '',
  remarks: '',
  photoUrl: '',
  clanAssociationId: props.templeId,
  userId: null // 关联会员ID
})

// 表单引用
const memberFormRef = ref()

// 表单校验规则
const memberFormRules = {
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (!value) {
          callback()
          return
        }
        // 中国大陆手机号码正则表达式
        const phoneReg = /^1[3-9]\d{9}$/
        if (!phoneReg.test(value)) {
          callback(new Error('请输入正确的手机号码格式'))
          return
        }
        // 检查是否是一些无效的号码段
        const invalidPrefixes = ['1700', '1701', '1702', '1703', '1704', '1705', '1706', '1707', '1708', '1709']
        const prefix = value.substring(0, 4)
        if (invalidPrefixes.includes(prefix)) {
          callback(new Error('请输入有效的手机号码'))
          return
        }
        callback()
      },
      trigger: 'blur'
    }
  ],
  email: [
    { required: false, message: '请输入电子邮箱', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (!value) {
          callback()
          return
        }
        // 邮箱正则表达式
        const emailReg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
        if (!emailReg.test(value)) {
          callback(new Error('请输入正确的邮箱格式'))
          return
        }
        // 检查邮箱长度
        if (value.length > 100) {
          callback(new Error('邮箱地址过长'))
          return
        }
        callback()
      },
      trigger: 'blur'
    }
  ]
}

// 添加计算属性：根据会员类型筛选可用职位
const availablePositions = computed(() => {
  return props.positions.filter(pos =>
    pos.memberType === memberForm.value.memberType ||
    pos.memberType === 'ALL'
  )
})

// 会员管理方法
const handleAddMember = () => {
  memberForm.value = {
    id: null,
    name: '',
    gender: '',
    birthDate: '',
    nativePlace: '',
    ethnicity: '',
    education: '',
    politicalStatus: '',
    specialty: '',
    phone: '',
    idCard: '',
    address: '',
    position: '',
    joinDate: '',
    memberType: 'A',
    // B类和C类特有字段
    companyName: '',
    companyPosition: '',
    registeredCapital: '',
    companyAddress: '',
    businessScope: '',
    // 其他字段
    email: '',
    familyRelation: '',
    remarks: '',
    photoUrl: '',
    clanAssociationId: props.templeId,
    userId: null // 关联会员ID
  }
  memberDialogVisible.value = true
  // 重置表单校验状态
  nextTick(() => {
    memberFormRef.value?.clearValidate()
  })
}

const handleEditMember = (row) => {
  memberForm.value = { ...row }
  memberDialogVisible.value = true
  // 重置表单校验状态
  nextTick(() => {
    memberFormRef.value?.clearValidate()
  })
}

const handleDeleteMember = async (row) => {
  ElMessageBox.confirm(
    `确定要删除会员 ${row.name} 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await ClanMemberAPI.deleteByIds(row.id)
      ElMessage.success('删除成功')
      // 删除成功后，重新获取会员列表
      await getMemberList()
    } catch (error) {
      console.error('删除会员失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => { })
}

// 添加宗亲会员
const saveMember = async () => {
  // 表单校验
  memberFormRef.value?.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning('请检查表单填写是否正确')
      return
    }

    if (!memberForm.value.name) {
      ElMessage.warning('请输入会员姓名')
      return
    }

    try {
      if (memberForm.value.id) {
        // 编辑现有会员
        await ClanMemberAPI.update(memberForm.value.id, memberForm.value)
        ElMessage.success('更新成功')
        // 更新成功后，重新获取会员列表
        await getMemberList()
      } else {
        // 添加新会员
        await ClanMemberAPI.addMember(memberForm.value)
        ElMessage.success('添加成功')
        // 添加成功后，重新获取会员列表
        await getMemberList()
      }
      memberDialogVisible.value = false
    } catch (error) {
      console.error('保存会员失败:', error)
      ElMessage.error('保存失败')
    }
  })
}

// 查看宗亲会员列表
const getMemberList = async () => {
  try {
    const response = await ClanMemberAPI.getPage({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      keywords: memberSearch.value || undefined
    })
    members.value = response.list || []
    totalMembers.value = response.total || 0
    emit('update:members', members.value)
  } catch (error) {
    console.error('获取会员列表失败:', error)
    ElMessage.error('获取会员列表失败')
  }
}

const handlePageChange = (page) => {
  currentPage.value = page
  getMemberList()
}

// 搜索处理
const handleSearch = () => {
  console.log(memberSearch.value);
  ClanMemberAPI.getPage({
    pageNum: 1,
    pageSize: 100,
    name: memberSearch.value || undefined
  }).then(response => {
    members.value = response.list || []
    totalMembers.value = response.total || 0
    emit('update:members', members.value)
  })
}

// 查看会员详情
const handleViewMember = (row) => {
  currentMember.value = row
  memberDetailVisible.value = true
}

// 添加照片上传相关方法
const handlePhotoSuccess = (response) => {
  memberForm.value.photoUrl = response.url
}

const beforePhotoUpload = (file) => {
  const isImage = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('上传照片只能是图片格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传照片大小不能超过 2MB!')
    return false
  }
  return true
}

// 组件挂载后获取会员列表
onMounted(() => {
  getMemberList()
})
</script>

<style scoped>
.toolbar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.image-preview {
  display: flex;
  gap: 20px;
  margin-top: 20px;
}

.preview-item {
  text-align: center;
}

.preview-item h4 {
  margin-bottom: 10px;
}

.form-tip {
  margin-left: 8px;
  font-size: 12px;
  color: #909399;
}

.avatar-uploader {
  text-align: center;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
  line-height: 120px;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style> 